package com.lemon.secondhandplatform.ui.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.lemon.secondhandplatform.broadcast.NetworkChangeReceiver;
import com.lemon.secondhandplatform.service.ShpService;

import butterknife.ButterKnife;
import cn.bmob.v3.Bmob;

/**
 * 封装了Activity
 * 创建的时候能够自动完成以下操作
 * 1.初始化Bmob
 * 2.ButterKnife.bind(this)
 * <p>
 * 销毁的时候能够自动完成以下操作
 * 1.解除绑定
 */
public class BaseActivity extends AppCompatActivity {

    protected NetworkChangeReceiver receiver;
    protected ShpService.ShpBinder binder;
    private Connection conn;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bmob.initialize(this, "ac9fb464bb393291d1772fab13f1662d");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService();
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        ButterKnife.bind(this);
    }

    /**
     * 绑定服务
     * 如果需要，就在onCreate方法中调用此方法
     */
    protected void bindService() {
        Intent intent = new Intent(getApplicationContext(), ShpService.class);
        conn = new Connection();
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

    /**
     * 解除绑定
     */
    protected void unbindService() {
        if (conn != null) {
            unbindService(conn);
            conn = null;
        }
    }

    /**
     * 绑定服务后
     * 如果需要在绑定服务后做一些操作，就重写此方法
     *
     * @param binder
     */
    protected void afterBindService(ShpService.ShpBinder binder) {

    }

    /**
     * 注册广播
     */
    private void registerReceiver() {
        receiver = new NetworkChangeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);
    }

    /**
     * 注销广播
     */
    private void unregisterReceiver() {
        unregisterReceiver(receiver);
    }

    class Connection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (ShpService.ShpBinder) service;
            afterBindService(binder);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            binder = null;
        }
    }
}
